package com.ruoyi.system.utils;

import java.lang.reflect.Field;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author: Zhangyuting
 * @Desctription: TODO
 * @Date: Created in 2025/6/3 21:48
 * @Version: 1.0
 */
public class DynamicSorter {

    public static <T> List<T> sortByField(List<T> list, String fieldName, boolean ascending) {
        Comparator<T> comparator = (a, b) -> {
            try {
                Field field = a.getClass().getDeclaredField(fieldName);
                field.setAccessible(true);

                // 获取字段值
                Comparable valueA = (Comparable) field.get(a);
                Comparable valueB = (Comparable) field.get(b);

                // 处理 null 值
                if (valueA == null && valueB == null) return 0;
                if (valueA == null) return ascending ? -1 : 1;
                if (valueB == null) return ascending ? 1 : -1;

                // 比较值
                return ascending ? valueA.compareTo(valueB) : valueB.compareTo(valueA);
            } catch (Exception e) {
                throw new RuntimeException("排序失败: " + e.getMessage(), e);
            }
        };

        return list.stream().sorted(comparator).collect(Collectors.toList());
    }

    public static <T> List<T> sortBySection(List<T> list, Function<T, String> sectionExtractor) {
        Comparator<T> comparator = (a, b) -> {
            String[] partsA = sectionExtractor.apply(a).split("\\.");
            String[] partsB = sectionExtractor.apply(b).split("\\.");

            int maxLength = Math.max(partsA.length, partsB.length);

            for (int i = 0; i < maxLength; i++) {
                // 处理级数不足的情况（例如 1.1 与 1.1.1）
                if (i >= partsA.length) return -1;
                if (i >= partsB.length) return 1;

                // 比较每一级的数值
                int valueA = Integer.parseInt(partsA[i]);
                int valueB = Integer.parseInt(partsB[i]);
                int result = Integer.compare(valueA, valueB);

                if (result != 0) {
                    return result; // 某一级不同，则返回结果
                }
                // 否则继续比较下一级
            }

            return 0; // 完全相同
        };

        return list.stream().sorted(comparator).collect(Collectors.toList());
    }

}
